package config

import (
	"encoding/json"
	"fmt"
	"log"
	"os"
	"time"
)

type Mysql struct {
	Addr     string `json:"addr,omitempty"`
	User     string `json:"user,omitempty"`
	Password string `json:"password,omitempty"`
	Database string `json:"database,omitempty"`
}

func (m *Mysql) GetDsnStr() string {
	dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", m.User, m.Password, m.Addr, m.Database)
	return dsn
}

type Server struct {
	Addr         string        `json:"addr,omitempty"`
	ReadTimeOut  time.Duration `json:"readTimeOut,omitempty"`
	WriteTimeOut time.Duration `json:"writeTimeOut,omitempty"`
}

type JWT struct {
	Issuer              string        `json:"issuer,omitempty"`
	TokenExpireDuration time.Duration `json:"tokenExpireDuration,omitempty"`
	Secrete             string        `json:"secrete,omitempty"`
}

type Consul struct {
	Addr string `json:"addr,omitempty"`
}

type Config struct {
	Mysql  Mysql
	Server struct {
		User    Server
		Gateway Server
		Note    Server
	}
	JWT    JWT
	Consul Consul
}

var conf *Config

func SetConfig(filename string) {
	var config *Config
	bytes, err := os.ReadFile(filename)
	if err != nil {
		log.Fatalln(err)
	}
	err = json.Unmarshal(bytes, &config)
	if err != nil {
		log.Fatalln(err)
	}
	conf = config
}

func GetConfig() *Config {
	return conf
}
